import { useLoadFilterData } from './useLoadFilterData'
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { findSubCategoryGoods } from '@/api/category'
import useFetch from './useFetch'
export function useLoadListData () {
  const { selectedTag, subCategoryData } = useLoadFilterData()
  const route = useRoute()
  const isfinished = ref(false)
  const goodList = ref([])
  // 商品详情列表
  const reqParams = ref({
    page: 1, // 页数
    pageSize: 10, // 条数
    categoryId: route.params.id, // 分类Id
    sortField: null, // 排序类别
    attrs: [], // 商品属性
    brandId: null // 品牌名称
  })
  // 规格筛选条件  同类的就进行覆盖只保留最后一项  不同类的不覆盖
  function toggleSelected (subOne, parentOne) {
    if (subOne == null) {
      selectedTag.value[parentOne.name] = null
      return
    }
    selectedTag.value[parentOne.name] = subOne
    const parentTags = Object.keys(selectedTag.value)
    const attrs = parentTags.filter(key => selectedTag.value[key]).map(key => ({
      groupName: key,
      propertyName: selectedTag.value[key].name
    }))
    // console.log(attrs, 'attrs')
    reqParams.value.attrs = attrs
    loadList()
  }

  // 排序功能实现
  // 声明一个list 包含所有可排序的字段
  const sortTypeList = [
    { name: '默认排序', type: null },
    { name: '最新商品', type: 'publishTime' },
    { name: '最高人气', type: 'orderNum' },
    { name: '评论最多', type: 'evaluateNum' }
  ]
  const curSortType = ref(null)
  function toggleSort (sortType) {
  // console.log(sortType)
    curSortType.value = sortType
    // 点击修改查询字段  之后立即重新发送请求 重新拉取列表
    // 先修改 再调用接口  注意先后顺序
    reqParams.value.sortField = sortType
    FetchFn()
  }

  const { fetch: FetchFn, isLoading } = useFetch(loadList)
  async function loadList (loadType) {
    if (loadType && loadType.formMore === true) {
      reqParams.value.page++
    }
    const res = await findSubCategoryGoods(reqParams.value)
    // console.log(loadType)
    goodList.value = [...goodList.value, ...res.result.items]
    if (res.result.items.length < reqParams.value.pageSize) {
      isfinished.value = true
    }
  }

  onMounted(() => {
    FetchFn()
  })

  return {
    toggleSelected,
    sortTypeList,
    toggleSort,
    curSortType,
    goodList,
    reqParams,
    FetchFn,
    isfinished,
    isLoading,
    subCategoryData,
    selectedTag
  }
}
